package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;

public class UserInput extends JPanel {
	private static final long serialVersionUID = 1L;
	
	private Chat _chat;
	
	private DefaultListModel _historyModel;
	private JList _history;
	private JScrollPane _historyView;
	
	private JTextField _input;

	public UserInput(Chat chat){
		super(new BorderLayout());
		
		_chat = chat;
		
		initialize();
		doPlumbing(chat);
	}
	
	private void initialize(){
		_historyModel = new DefaultListModel();
		
		_history = new JList(_historyModel);
		_historyView = new JScrollPane();
		_historyView.setViewportView(_history);
		_historyView.setMinimumSize(new Dimension(600,300));
		this.add(_historyView, BorderLayout.CENTER);
		
		
		_input = new JTextField();
		_input.setMinimumSize(new Dimension(0,30));
		_input.setMaximumSize(new Dimension(0,30));
		this.add(_input, BorderLayout.SOUTH);
		
		this.validate();
	}
	
	private void doPlumbing(Chat chat)
	{
		_chat.addMessageListener(new MessageListener(){
			@Override
			public void processMessage(Chat chat, Message message) {
				String name = StringUtils.parseName(message.getFrom());
				_historyModel.addElement(name+" said: "+message.getBody());
				scrollToBottomOfJList();
			}
		});
		
		_input.addKeyListener(new KeyAdapter(){
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					e.consume();
					
					String message = _input.getText();
					_input.setText("");
					
					if(message.trim() == "")
						return;
					
					_historyModel.addElement("me said: "+message);
					scrollToBottomOfJList();
					
					try {
						_chat.sendMessage(message);
					} catch (XMPPException ex) {
						ex.printStackTrace();
					}
				}
			}
			
		});
	}
	
	private void scrollToBottomOfJList() {
		_history.ensureIndexIsVisible(_historyModel.size() - 1);
	}
}
